package com.hontech.bv.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.Button
import android.widget.FrameLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hontech.bv.R
import com.hontech.bv.model.Version
import com.hontech.bv.task.onClick
import com.hontech.bv.ui.view.adapter.FirmUpdateAdapter

class SingleFirmView(ctx: Context, attrs: AttributeSet) : FrameLayout(ctx, attrs) {

    private val btnHide: Button
    private val tvTitle: TextView
    private val rv: RecyclerView

    private val destId: Int
    private val name: String

    private val adapter: FirmUpdateAdapter

    init {
        val view = LayoutInflater.from(ctx).inflate(R.layout.view_firm_single, this)
        btnHide = view.findViewById(R.id.id_single_firm_btn_hide_or_get)
        tvTitle = view.findViewById(R.id.id_single_firm_tv_title)
        rv = view.findViewById(R.id.id_single_firm_rv)

        val style = ctx.obtainStyledAttributes(attrs, R.styleable.SingleFirmView)
        destId = style.getInteger(R.styleable.SingleFirmView_firm_dest, -1)
        if (destId == -1) {
            throw IllegalStateException("destId没有设置")
        }
        name = style.getString(R.styleable.SingleFirmView_firm_name) ?: throw IllegalStateException("没有设置名称")
        style.recycle()

        init()
        btnHide.onClick(::onClickHide)

        adapter = FirmUpdateAdapter(destId)
        rv.adapter = adapter
        rv.layoutManager = LinearLayoutManager(ctx, LinearLayoutManager.HORIZONTAL, false)
    }

    private fun init() {
        btnHide.text = "获取"
        tvTitle.text = name
        rv.visibility = GONE
    }

    private suspend fun onClickHide() {
        if (rv.visibility == GONE) {
            doGet()
            btnHide.text = "隐藏"
        } else {
            rv.visibility = GONE
            btnHide.text = "获取"
        }
        tvTitle.text = "${name}:${Version.getVerByDest(destId)}"
    }

    private suspend fun doGet() {
        rv.visibility = VISIBLE
        adapter.getFirm()
    }
}

